<?php

namespace jueqi;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\common\model\SmsRecord;
use Darabonba\OpenApi\Models\Config;
use Exception;

/**
 * 阿里云短信发送
 */
class AliYunSms
{

    /**
     * 发送短信
     * @param $mobile
     * @param $content
     * @param $templateCode
     * @param int $activity_id
     * @param string $msg
     * @return bool
     */
    public static function sendSms($mobile, $content, $templateCode, $activity_id = 0, string &$msg = ''): bool
    {
        if (empty($mobile)) {
            $msg = '手机号不能为空！';
            return false;
        }
        if (empty($content)) {
            $msg = '短信内容不能为空！';
            return false;
        }
        if(empty($templateCode)){
            $msg = '短信模板编号未配置！';
            return false;
        }
        $smsConfig = get_sys_config("", 'sms_config');
        if (empty($smsConfig)) {
            $msg = '短信未配置';
            return false;
        }
        $accessKeyId     = $smsConfig['app_key_id'] ?? ''; // AccessKey_ID
        $accessKeySecret = $smsConfig['acc_key_secret'] ?? ''; // Access_Key_Secret
        $smsSign         = $smsConfig['sms_sign'] ?? ''; // 短信签名
        if (empty($accessKeyId) || empty($accessKeySecret)) {
            $msg = '短信配置错误';
            return false;
        }
        $sendCode = json_decode($content, true)['code'] ?? '';
        $client         = self::createClient($accessKeyId, $accessKeySecret);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers"  => $mobile,
            "signName"      => $smsSign,
            "templateCode"  => $templateCode,
            "templateParam" => $content
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res     = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            if(empty($res) || !isset($res->body) || !isset($res->body->code)){
                $msg = '短信发送失败！';
                return false;
            }
            if($res->body->code != 'OK'){
                $msg = '短信发送失败！';
                if(isset($res->body->message)){
                    $msg = $res->body->message;
                }
                return false;
            }
            $code    = $res['Code'] ?? ''; // 状态码
            $Message = $res['Message'] ?? ''; // 失败原因
            $data    = array(
                'type'            => 1,
                'mobile'          => $mobile,
                'content'         => $content,
                'activity_id'     => $activity_id,
                'template_number' => $templateCode,
                'create_time'     => time(),
                'code'            => $sendCode,
                'expire_time'     => time(),
            );
            if ($code === 'OK') {
                $data['status']      = 1;
                $data['expire_time'] = time() + 300;
                (new SmsRecord())->save($data);
                return true;
            }
            $msg             = $Message;
            if(empty($msg)){
                $msg = '短信发送失败！';
            }
            $data['status']  = 2;
            $data['message'] = $msg;
            (new SmsRecord())->save($data);
            return false;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
            $msg  = $error->message;
            $data = array(
                'type'            => 1,
                'mobile'          => $mobile,
                'content'         => $content,
                'activity_id'     => $activity_id,
                'template_number' => $templateCode,
                'create_time'     => time(),
                'code'            => $sendCode,
                'expire_time'     => time(),
                'status'          => 2,
                'msg'             => $msg
            );
            (new SmsRecord())->save($data);
            return false;
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param $accessKeyId
     * @param $accessKeySecret
     * @return Dysmsapi
     */
    public static function createClient($accessKeyId, $accessKeySecret): Dysmsapi
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId"     => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret,
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $config->protocol = "HTTP";
        return new Dysmsapi($config);
    }
}